<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`设置刷新`">
    <el-form
      ref="jobRefreshFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="120px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <div class="refresh-box">
        <div class="left-box">
          <div class="info-box">
            <el-alert
              title="刷新说明 "
              type="success"
              :description="`每间隔${dialogData.itemInfo.step || 0}分钟，刷新一次，消耗${
                dialogData.itemInfo.refreshCoin || 0
              }当家币`"
              show-icon
              :closable="false"
              style="width: 90%"
            />
          </div>
          <el-form-item label="刷新次数">
            <el-input-number
              style="width: 80%; text-align: left"
              placeholder="请输入刷新次数"
              size="large"
              :min="1"
              v-model="dialogData.itemInfo.refreshCnt"
            />
          </el-form-item>
          <el-form-item label="刷新时间">
            <el-time-select
              v-model="dialogData.itemInfo.refreshDate"
              start="06:00"
              step="00:15"
              end="23:30"
              size="large"
              placeholder="请选择刷新时间"
              style="width: 80%"
            />
          </el-form-item>
          <el-form-item label="刷新间隔">
            <el-input-number
              style="width: 80%; text-align: left"
              placeholder="请输入刷新次数"
              size="large"
              :min="1"
              v-model="dialogData.itemInfo.step"
            />
          </el-form-item>
          <el-form-item label="每天刷新">
            <el-radio-group v-model="dialogData.itemInfo.flagEveryday">
              <el-radio label="Y">是</el-radio>
              <el-radio label="N">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="结束时间">
            <el-date-picker
              v-model="dialogData.itemInfo.endDate"
              type="date"
              placeholder="请选择结束时间"
              style="width: 80%"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button
              type="primary"
              class="refresh-now-btn"
              :icon="Timer"
              size="large"
              @click="handleSubmit"
              :loading="btnLoading"
            >
              开启预约刷新
            </el-button>
            <el-button type="primary" text class="refresh-now-btn" @click="handleStop">停止刷新</el-button>
          </el-form-item>
        </div>
        <div class="right-box">
          <el-button type="primary" class="refresh-now-btn" :icon="Refresh" @click="handleRefreshOnce">立即刷新一次</el-button>
        </div>
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { JobRefreshEntity } from "@/biz/interface/JobType";
import { Timer, Refresh } from "@element-plus/icons-vue";
import { getJobRefreshApi, runonceJobRefreshApi, saveJobRefreshApi, stopJobRefreshApi } from "@/api/modules/cpyjob/ft";
//页面的数据
interface JobRefreshDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  //当前的数据对象
  itemInfo: JobRefreshEntity;
  //其它的数据都继续在这里加
}
//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<JobRefreshDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  itemInfo: {
    jobId: "",
    // 每天刷新标记
    flagEveryday: "N",
    // 刷新次数
    refreshCnt: 1,
    // 刷新时间
    refreshDate: "",
    // 间隔 分钟
    step: 15,
    refreshCoin: ""
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;

  initItemInfo();

  if (dialogData.rowData?.id) {
    dialogData.itemInfo.jobId = dialogData.rowData?.id;
    getJobRefreshApi({ jobId: dialogData.itemInfo.jobId }).then(res => {
      if (res.data) {
        dialogData.itemInfo = res.data as unknown as JobRefreshEntity;
        if (dialogData.itemInfo.id) {
          dialogData.optType = OptEnum.EDIT;
        } else {
          dialogData.optType = OptEnum.CREATE;
          dialogData.itemInfo.jobId = dialogData.rowData?.id;
        }
      }
    });
  }

  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    jobId: "",
    // 每天刷新标记
    flagEveryday: "Y",
    // 刷新次数
    refreshCnt: 1,
    // 刷新时间
    refreshDate: "",
    // 间隔 分钟
    step: 30,
    // 刷新结束时间
    refreshCoin: ""
  };
};

//数据较验
const rules = reactive({
  title: [{ required: true, message: "请填写标题", trigger: "blur" }],
  contactor: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  contactPhone: [{ required: true, message: "请填写联系电话", trigger: "blur" }],
  address: [{ required: true, message: "请填写详细面试地址", trigger: "blur" }]
});

// 停止刷新
const handleStop = async () => {
  if (dialogData.itemInfo.jobId) {
    let res = await stopJobRefreshApi({ jobId: dialogData.itemInfo.jobId });
    if (res && res.data) {
      ElMessage.success({ message: `预约刷新已停止！` });
      //刷新列表数据
      emits("refresh-list");
      dialogVisible.value = false;
    }
  }
};

// 立即刷新一次
const handleRefreshOnce = async () => {
  if (dialogData.itemInfo.jobId) {
    let res = await runonceJobRefreshApi({ jobId: dialogData.itemInfo.jobId });
    if (res && res.data) {
      ElMessage.success({ message: `刷新完成！` });
    }
  }
};

// 提交数据（新增/编辑）
const jobRefreshFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobRefreshFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      //提交数据
      let res = await saveJobRefreshApi({
        ...dialogData.itemInfo
      });
      if (res.data) {
        ElMessage.success({ message: `预约刷新已开启！` });
        //刷新列表数据
        emits("refresh-list");
        dialogVisible.value = false;
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.refresh-box {
  display: flex;
  justify-content: space-around;
  align-items: center;

  .left-box {
    flex: 1;

    .info-box {
      margin: 15px 30px;
    }
  }

  .right-box {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;

    .refresh-now-btn {
      width: 80%;
      height: 120px;
      border-radius: 10px;
      font-size: 1.6rem;
      font-weight: 600;
    }
  }
}
</style>
